/*
 * @Author: 胡海
 * @Date: 2020-02-10 19:39:49
 * @LastEditors: 胡海
 * @LastEditTime: 2020-03-08 15:32:07
 * @Description: 
 */
const Router = require('koa-router')
const {
    Auth
} = require('../../../middlewares/auth')

const {
    Wgoods
} = require('../../models/w-goodsM')
const {
    Wimg
} = require('../../models/w-imgM')
const {
    addGoodsValidator,
    editGoodsValidator
} = require('../../validators/w-goodsV')
const {
    PositiveIdValidator,
    PaginateValidator
} = require('../../validators/common')

const upload = require('../../../core/upImg')

const router = new Router({
    prefix: '/v1/w-home'
})

router.post('/addGoods', new Auth().m, async (ctx) => { // 新增产品
    const v = await new addGoodsValidator().validate(ctx)
    const data = await Wgoods.addgoods(ctx, v)
    throw new global.errs.Success()
})
router.post('/editGoods', new Auth().m, async (ctx) => { // 修改产品
    const v = await new editGoodsValidator().validate(ctx)
    const data = await Wgoods.editGoods(ctx, v)
    throw new global.errs.Success()
})
router.post('/delGoods', new Auth().m, async (ctx) => { // 删除产品
    const v = await new PositiveIdValidator().validate(ctx)
    const data = await Wgoods.delGoods(ctx, v)
    throw new global.errs.Success()
})
router.post('/listGoods', new Auth().m, async (ctx) => { // 列表
    const v = await new PaginateValidator().validate(ctx)
    const data = await Wgoods.list(ctx, v)
    ctx.body = {
        error_code: 0,
        msg: 'ok',
        data
    }
})
router.post('/uploadImg', async (ctx) => { // 上传
    const v = await new PositiveIdValidator().validate(ctx)
    const fileName = upload(ctx)
    await Wimg.addImg(`img/${fileName}`, v)
    ctx.body = {
        error_code: 0,
        msg: 'ok',
        data: {
            img: `img/${fileName}`
        }
    }
})

module.exports = router